package com.xfcode.config;


import lombok.Data;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "es")
@EnableConfigurationProperties(ElasticsearchConfig.class)
@Data
public class ElasticsearchConfig {
    private String  masterHost;
    private Integer masterPort;
    private boolean enableAuth;
    private String masterUserName;
    private String masterPassword;
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        HttpHost host=new HttpHost(masterHost, masterPort, HttpHost.DEFAULT_SCHEME_NAME);
        RestClientBuilder builder=RestClient.builder(host);
        if(enableAuth) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(masterUserName, masterPassword));
            builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
        }
        return new RestHighLevelClient( builder);
    }
}
